// src/main/java/com/ruoyi/chat/util/PartitionManager.java

package com.reliable.service.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class PartitionManager {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void createPartitionsIfNeeded(LocalDateTime minTime, LocalDateTime maxTime) {
        YearMonth start = YearMonth.from(minTime.withDayOfMonth(1));
        YearMonth end = YearMonth.from(maxTime.withDayOfMonth(1));

        Set<String> existingPartitions = getExistingPartitions();

        YearMonth current = start;
        while (!current.isAfter(end)) {
            String partitionName = "chat_messages_" + current.format(DateTimeFormatter.ofPattern("yyyy_MM"));
            if (!existingPartitions.contains(partitionName)) {
                String startMonth = current.atDay(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
                String endMonth = current.plusMonths(1).atDay(1).format(DateTimeFormatter.ISO_LOCAL_DATE);
                
                String sql = String.format(
                    "CREATE TABLE IF NOT EXISTS %s PARTITION OF chat_messages FOR VALUES FROM ('%s') TO ('%s')",
                    partitionName, startMonth, endMonth
                );
                jdbcTemplate.execute(sql);
                System.out.println("✅ 创建分区: " + partitionName);
            }
            current = current.plusMonths(1);
        }
    }

    private Set<String> getExistingPartitions() {
        String sql = "SELECT tablename FROM pg_tables WHERE tablename LIKE 'chat_messages_%'";
        return jdbcTemplate.queryForList(sql, String.class).stream().collect(Collectors.toSet());
    }
}